//
//  NBMainViewController.swift
//  NBSinaWeibo
//
//  Created by ac on 16/5/19.
//  Copyright © 2016年 ac. All rights reserved.
//

import UIKit

class NBMainViewController: UITabBarController {

    override func viewDidLoad() {
        super.viewDidLoad()

        //添加子控制器
        addChildViewControllers()
        
        //设置tabBar中间的加号图片
        let myTabBar = NBMainTabBar()
//        print(tabBar.classForCoder)
        setValue(myTabBar, forKey: "tabBar")
//        print(tabBar.classForCoder)
        
    }

    private func addChildViewControllers() {
        addChildViewController(NBHomeTableViewController(), title: "首页", imageName: "tabbar_home", index: 0)
        addChildViewController(NBMessageTableViewController(), title: "消息", imageName: "tabbar_message_center", index: 1)
        addChildViewController(NBDiscoverTableViewController(), title: "发现", imageName: "tabbar_discover", index: 2)
        addChildViewController(NBProfileTableViewController(), title: "我的", imageName: "tabbar_profile", index: 3)
        
    }
    private func addChildViewController(vc: UIViewController,title: String,imageName: String, index: Int) {
        
        
        
        let tabbaritem = NBTabbarItem()
        vc.tabBarItem = tabbaritem
        vc.title = title
        vc.tabBarItem.image = UIImage(named: imageName)
        vc.tabBarItem.selectedImage = UIImage(named: imageName + "_selected")?.imageWithRenderingMode(.AlwaysOriginal)
        vc.tabBarItem.setTitleTextAttributes([NSForegroundColorAttributeName:UIColor.orangeColor()], forState: .Selected)
//        tabBar.tintColor = UIColor.orangeColor()
        vc.tabBarItem.titlePositionAdjustment = UIOffset(horizontal: 0, vertical: -3)
        vc.tabBarItem.tag = index
        
        let nav = NBBaseViewController(rootViewController: vc)
        addChildViewController(nav)
        
        
    }
    
    override func tabBar(tabBar: UITabBar, didSelectItem item: UITabBarItem) {
        var index = 0
        for v in tabBar.subviews {
            
            if v.isKindOfClass(NSClassFromString("UITabBarButton")!) {
                if item.tag == index {
                    for subView in v.subviews {
                        if subView.isKindOfClass(NSClassFromString("UITabBarSwappableImageView")!) {
                            subView.transform = CGAffineTransformMakeScale(0.5, 0.5)
                            UIView.animateWithDuration(0.5, delay: 0, usingSpringWithDamping: 0.5, initialSpringVelocity: 2, options: [], animations: {
                                subView.transform = CGAffineTransformIdentity
                                }, completion: nil)
                        }
                    }
                }
                index += 1
            }
            
            
        }
    }
    
}
